package com.dameng.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dameng.system.entity.SystemRole;
import com.dameng.system.entity.SystemUser;
import com.dameng.system.entity.SystemUserRole;
import com.dameng.system.mapper.SystemRoleMapper;
import com.dameng.system.mapper.SystemUserMapper;
import com.dameng.system.mapper.SystemUserRoleMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    SystemUserMapper systemUserMapper;

    @Resource
    SystemUserRoleMapper systemUserRoleMapper;

    @Resource
    SystemRoleMapper systemRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("用户名不能为空！");
        }
        SystemUser user = systemUserMapper.selectOne(
                new QueryWrapper<SystemUser>().lambda().eq(SystemUser::getUsername, username)
        );
        if (user == null) {
            throw new UsernameNotFoundException("账户不存在！");
        }
        List<SystemUserRole> userRoles = systemUserRoleMapper.selectList(
                new QueryWrapper<SystemUserRole>().lambda().eq(SystemUserRole::getUserId, user.getUserId())
        );
        if (userRoles != null && !userRoles.isEmpty()) {
            List<String> roleIds = userRoles.stream().map(SystemUserRole::getRoleId).collect(Collectors.toList());
            List<SystemRole> roles = systemRoleMapper.selectList(
                    new QueryWrapper<SystemRole>().lambda().in(SystemRole::getRoleId, roleIds)
            );
            user.setSystemRoles(roles);
        }
        return user;
    }
}
